package com.ynet.middleground.oss.controller;

import java.security.Principal;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.ynet.core.common.ServiceResult;

/**
 * @author liulx
 * @description TODO
 * @date 2020-10-22 15:19
 */
@Controller
public class UnifiedTokenEndpoint {

    @Resource(name = "tokenEndpoint")
    private TokenEndpoint tokenEndpoint;

    @RequestMapping(value = "/oauth/token", method = RequestMethod.POST)
    public ResponseEntity postAccessToken(Principal principal, @RequestParam Map<String, String> parameters)
        throws HttpRequestMethodNotSupportedException {
        ResponseEntity<OAuth2AccessToken> entity = tokenEndpoint.postAccessToken(principal, parameters);
        OAuth2AccessToken token = entity.getBody();
        ServiceResult<OAuth2AccessToken> result = new ServiceResult<>();
        result.setResult(token);
        return getResponse(result);
    }

    private ResponseEntity<ServiceResult<OAuth2AccessToken>> getResponse(ServiceResult<OAuth2AccessToken> res) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Cache-Control", "no-store");
        headers.set("Pragma", "no-cache");
        headers.set("Content-Type", "application/json;charset=UTF-8");
        return new ResponseEntity<>(res, headers, HttpStatus.OK);
    }

}
